# encoding = utf-8
class InfosController < ApplicationController

  before_filter :authenticate_user!, :only => [:new, :create, :edit, :update]

  def new
    if params[:id] == 'deal'
      @dealurl = 1
    end
    @info = Info.new
    @buildings = Building.all
    @action = {:action => 'create'}
    @action_title = '添加送餐地址'
  end

  def create
    info_new = params[:info]
    info_new[:user_id] = current_user.id
    @info = Info.new(info_new)
    if @info.building_id!=0 and @info.save
      flash[:success] = '添加送餐地址成功'
      if params[:dealurl].nil?
        redirect_to '/users/info'
      else
        redirect_to '/deals/new'
      end
    else
      if @info.building_id == 0
        flash[:error] = '请选择您所在的办公楼'
      elsif @info.name.blank?
        flash[:error] = '请填写您的姓名'
      elsif @info.phone.blank?
        flash[:error] = '请填写您的电话号码'
      elsif @info.floor.blank?
        flash[:error] = '请填写您所在的楼层'
      elsif @info.company_name.blank?
        flash[:error] = '请填写您的公司名称'
      end
      @buildings = Building.all
      @action = {:action => 'create'}
      if !params[:dealurl].nil?
        @dealurl = 1
      end
      render  :action => 'new'
    end
  end

  def edit
    @info = current_user.info
    @buildings = Building.all
    @action = {:action => 'update', :id => @info.id}
    @action_title = '编辑送餐地址'
    render  :action => 'new'
  end

  def update
    info_update = params[:info]
    info_current = current_user.info
    if info_update[:building_id] == '0' && !info_current.building_id.nil?
      info_update[:building_id] = info_current.building_id.to_s
    end

    if info_update[:building_id] == '0'
      flash[:error] = '请选择您所在的办公楼'
    elsif info_update[:name].blank?
      flash[:error] = '请填写您的姓名'
    elsif info_update[:phone].blank?
      flash[:error] = '请填写您的电话号码'
    elsif info_update[:floor].blank?
      flash[:error] = '请填写您所在的楼层'
    elsif info_update[:company_name].blank?
      flash[:error] = '请填写您的公司名称'
    else
      Info.update(info_current.id, params[:info])
      flash[:success] = '更新送餐地址成功'
      redirect_to '/users/info'
      return
    end

    redirect_to :action => :edit
  end
end
